package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.githang.statusbar.StatusBarCompat;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.adapter.BrandListAdapter;
import com.ramos.kuaixiao.db.BrandDB;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.entity.ShopNew;
import com.ramos.kuaixiao.utils.CommonLoading;
import com.ramos.kuaixiao.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

public class ShopListActivity extends BaseAllTabActivity implements View.OnClickListener {
    private static String TAG = "ShopDetailActivity";
    private Context mContext;
    private LinearLayout title_reback;
    private TextView title_text;
    public final static int UPLOAD_SUCCESS = 1000;
    public final static int UPLOAD_FAIL = 1001;
    public final static int SCANNIN_GREQUEST_CODE = 0xb1;
    Customer mCustomer;
    ListView lv_goods;
    ImageView iv_scan;
    ImageView search;
    ImageView shopmall;
    CommonLoading loading1;
    private List<ShopNew> shopList = new ArrayList<>();
    private List<String> myTypeList = new ArrayList<>();
    BrandListAdapter mAdapter;
    int oldVisibleItem = 0;
    BrandDB mBrandDB;
    private RelativeLayout re_home_shop;
    private RelativeLayout re_home_order;
    private RelativeLayout re_home_task;
    private RelativeLayout re_home_my;
    private TextView tv_home_shop;
    private TextView tv_home_order;
    private TextView tv_home_task;
    private TextView tv_home_my;
    private ImageView ib_home_shop;
    private ImageView ib_home_order;
    private ImageView ib_home_task;
    private ImageView ib_home_my;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_list);
        mContext = this;
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.title), false);
        initView();
        initTabView();
    }

    private void initView() {
        title_reback = (LinearLayout) findViewById(R.id.title_reback);
        title_reback.setOnClickListener(this);

        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("商品");

        lv_goods = (ListView) findViewById(R.id.lv_goods);
        iv_scan = (ImageView) findViewById(R.id.iv_scan);
        iv_scan.setOnClickListener(this);
        search = (ImageView) findViewById(R.id.search);
        search.setOnClickListener(this);
       /* shopmall = (ImageView) findViewById(R.id.shopmall);
        shopmall.setOnClickListener(this);*/

        mCustomer = (Customer) getIntent().getExtras().get("customer");

        initLocalDB();
    }


    private void initTabView() {
        re_home_shop = (RelativeLayout) findViewById(R.id.re_home_shop);
        re_home_order = (RelativeLayout) findViewById(R.id.re_home_order);
        re_home_task = (RelativeLayout) findViewById(R.id.re_home_task);
        re_home_my = (RelativeLayout) findViewById(R.id.re_home_my);
        re_home_shop.setOnClickListener(this);
        re_home_order.setOnClickListener(this);
        re_home_task.setOnClickListener(this);
        re_home_my.setOnClickListener(this);

        ib_home_shop = ((ImageView) findViewById(R.id.ib_home_shop));
        ib_home_order = ((ImageView) findViewById(R.id.ib_home_order));
        ib_home_task = ((ImageView) findViewById(R.id.ib_home_task));
        ib_home_my = ((ImageView) findViewById(R.id.ib_home_my));

        tv_home_shop = ((TextView) findViewById(R.id.tv_home_shop));
        tv_home_order = ((TextView) findViewById(R.id.tv_home_order));
        tv_home_task = ((TextView) findViewById(R.id.tv_home_task));
        tv_home_my = ((TextView) findViewById(R.id.tv_home_my));

        ib_home_shop.setImageResource(R.drawable.tab_infomation_clk);
        tv_home_shop.setTextColor(getResources().getColor(R.color.title));

        ib_home_order.setImageResource(R.drawable.tab_schedule);
        tv_home_order.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_task.setImageResource(R.drawable.tab_service);
        tv_home_task.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_my.setImageResource(R.drawable.tab_contacts);
        tv_home_my.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

    }

    private void initLocalDB() {
        mBrandDB = new BrandDB();
        List<ShopNew> list = mBrandDB.findAllNoEmptyBrand();
        initList(list);
    }

    public void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    Log.d(TAG, "result " + msg.obj.toString());
                    initShopNew(msg.obj.toString());
                    break;
                case UPLOAD_FAIL:
                    Log.d(TAG, "result fail");
                    ToastUtils.show("获取数据失败！");
                    break;
                default:
                    break;
            }
        }
    };

    private void initShopNew(String s) {
        JSONObject jsonObejct = JSONObject.parseObject(s);
        JSONObject data = jsonObejct.getJSONObject("data");
        JSONArray array;
        if (data.getJSONArray("rows") == null) {
            if (data.getJSONArray("row") == null) {
                return;
            } else {
                array = data.getJSONArray("row");
            }
        } else {
            array = data.getJSONArray("rows");
        }
        shopList = JSONArray.parseArray(array.toString(), ShopNew.class);
        initList(shopList);
    }

    private void initList(List<ShopNew> shopList){
        for (int i = 0; i < shopList.size(); i++) {
            ShopNew shopType = shopList.get(i);
            myTypeList.add(shopType.getBrandName());
        }
        mAdapter = new BrandListAdapter(mContext, myTypeList);
        lv_goods.setAdapter(mAdapter);
        lv_goods.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String brand = (String)parent.getAdapter().getItem(position);
                Intent intent1 = new Intent(mContext, ShopOrderActivity.class);
                intent1.putExtra("customer", mCustomer);
                intent1.putExtra("brand", brand);
                intent1.putExtra("position", position);
                startActivity(intent1);
            }
        });

        //定义一个放大动画
        final ScaleAnimation circularAnim = new ScaleAnimation(1.0f, 50f, 1.0f, 50f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        circularAnim.setDuration(500);
        circularAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                //mImageView.setVisibility(View.VISIBLE);    // 注意： 不该在动画开始时set VISIBLE，不然会看不到动画
            }
            @Override
            public void onAnimationEnd(Animation animation) {
                //mImageView.setVisibility(View.GONE);
                // TODO Something...
            }
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

        lv_goods.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem > oldVisibleItem) {
                    // 向上滑动

                    iv_scan.setVisibility(View.VISIBLE);   //而应该在开始动画之前set VISIBLE
                    //iv_scan.startAnimation(circularAnim);
                }
                if (firstVisibleItem < oldVisibleItem) {
                    // 向下滑动
                    iv_scan.setVisibility(View.GONE);   //而应该在开始动画之前set VISIBLE
                    //iv_scan.startAnimation(circularAnim);
                }
                oldVisibleItem = firstVisibleItem;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_reback:
                finish();
                break;
            case R.id.re_home_shop:
                showMain(1);
                break;
            case R.id.re_home_order:
                showMain(2);
                break;
            case R.id.re_home_task:
                showMain(3);
                break;
            case R.id.re_home_my:
                showMain(4);
                break;
           case R.id.search:
                startNewActivity(ProductResultActivity.class);
                break;
            case R.id.iv_scan:
                Intent intent1 = new Intent();
                intent1.setClass(mContext, CaptureActivity.class);
                intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent1, SCANNIN_GREQUEST_CODE);
                break;
            case R.id.shopmall:
                Intent intent = new Intent();
                intent.setClass(this, MainActivity.class);
                //一定要指定是第几个pager，因为要跳到ThreeFragment，这里填写2
                intent.putExtra("id", 2);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (resultCode == SCANNIN_GREQUEST_CODE) {
                Log.d(TAG, "onActivityResult " + data.getExtras().getString("scan_code"));
                //searchview.setQuery(data.getExtras().getString("scan_code"), true);
                Intent intent = new Intent(ShopListActivity.this, ProductResultActivity.class);
                intent.putExtra("scan_code", data.getExtras().getString("scan_code"));
                startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startNewActivity(Class<?> activityClass) {
        Intent intent = new Intent(mContext, activityClass);
        intent.putExtra("customer", mCustomer);
        startActivity(intent);
    }
}
